package com.jdjt.dams.goods;

import java.io.File;
import java.util.Date;
import java.util.List;

import com.base.common.utils.StringUtil;
import com.base.common.utils.TimeUtil;
import com.base.common.utils.file.FileUtil;
import com.jfinal.upload.UploadFile;

public class GoodsImageService 
{
	String path;
	String fileName;
	
	//添加图片 0:正确； 1：创建图片失败;2：保存商品图片表失败;3:商品图片大于4张图片;
	public String insertGoodsImage(UploadFile uploadFile,String merchant_umber,String goodsId) throws Exception
	{	
		String resouce = null;	
		//拼接图片路径
		path=uploadFile.getSaveDirectory()+"busi\\"+merchant_umber;
		//查询文件夹下面的文件
		List<String> list=FileUtil.searchAllFile(path);
		String fileName=TimeUtil.format("yyyyMMdd",new Date().getTime())+"_sp_"+(list.size()+1)+"_s_"+StringUtil.random(8)+".jpg";
		boolean bool=uploadFile.getFile().renameTo(new File(path,fileName));
		//判断图片是否保存
		if(bool)
		{
			List<GoodsImageModel> goodsImageList=GoodsImageModel.dao.find("SELECT * FROM cshm_goods_image where goods_id=?",goodsId);
			if(goodsImageList.size()>=4)
			{
				resouce="3";
			}
			else{
				//添加表数据
				GoodsImageModel goodsImage=new GoodsImageModel();
				goodsImage.set("goods_id", goodsId);
				goodsImage.set("image_url", "upload/busi/"+merchant_umber+"/"+fileName);
				goodsImage.set("thumbnail", "upload/busi/"+merchant_umber+"/"+fileName);
				bool=goodsImage.save();
				//判断表数据添加是否成功
				if(!bool)
				{
					resouce="2";
				}
				else
				{
					resouce="0";
				}
			}
		}
		else
		{
			resouce="1";
		}
		return resouce;
	}
	
	public List<GoodsImageModel> findGoodsImage(String goodsId){
		List<GoodsImageModel> goodsImageModelList=GoodsImageModel.dao.find("select * FROM cshm_goods_image where goods_id=?", goodsId);
		return goodsImageModelList;
	}
	
}
